package com.glsc.ngateway.platform.controller.it;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.glsc.ngateway.common.api.common.enums.PageConstant;
import com.glsc.ngateway.common.api.platform.dto.it.ParamSearchServerDto;
import com.glsc.ngateway.common.api.platform.dto.it.ServerDeviceExport;
import com.glsc.ngateway.common.api.platform.dto.it.ServerDeviceExportFull;
import com.glsc.ngateway.common.api.platform.dto.user.PlatformUserDto;
import com.glsc.ngateway.common.api.platform.resp.PlatformResponse;
import com.glsc.ngateway.common.base.domain.mysql.gateway.platform.it.ItServerDevice;
import com.glsc.ngateway.common.base.utils.NGSMDateTimeFormatter;
import com.glsc.ngateway.platform.aspect.UserCache;
import com.glsc.ngateway.platform.service.UserService;
import com.glsc.ngateway.platform.service.it.ServerService;
import com.glsc.ngateway.platform.utils.ExcelUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URLEncoder;
import java.text.ParseException;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import static com.glsc.ngateway.common.api.common.enums.Constant.SERVER_ADMIN;

@RestController
@RequestMapping("/it/server")
@Api(value = "服务管理", tags = {"服务管理"})
public class ServerManageController {

    @Autowired
    private ServerService serverService;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private UserCache userCache;
    @Autowired
    private UserService userService;
    @Value("${export.it}")
    public String itpath;

    // 查询物理设备清单
//    @RequestMapping(method = RequestMethod.GET, value = "query")
//    @ApiOperation(value = "查询物理设备清单", notes = "查询物理设备清单")
//    public PlatformResponseNew queryServerList(
//            @ApiParam(value = "页码从1开始") @RequestParam(required = false) Integer pageNo,
//            @ApiParam(value = "每页显示条数 默认10") @RequestParam(required = false) Integer pageSize) {
//
//        if (pageNo == null) {
//            pageNo = 1;
//        }
//        if (pageSize == null) {
//            pageSize = PageConstant.PageSize;
//        }
//        PlatformUserDto user = userCache.get(request);
//        String userid = user.getUserid();
//            Set<String> roleNames = user.getRoles().stream().map(role -> role.getName()).collect(Collectors.toSet());
//                if ("itadmin".equals(user.getUsername()) || roleNames.contains("itadmin")) {
//                userId = null;
//            }
//        Page<ItServerDevice> result = serverService.queryServer(pageNo, pageSize, userid);
//        PlatformResponseNew ret = PlatformResponseNew.success();
//        ret.setData(result);
//        return ret;
//    }

    /*
     * 提交或修改项目
     */
    @RequestMapping(method = RequestMethod.POST, value = "addOrUpdate")
    @ApiOperation(value = "提交或修改项目", notes = "提交或修改项目")
    public PlatformResponse<Void> addOrUpdateServer(@RequestBody ItServerDevice itServerDevice) throws ParseException {

        if (!StringUtils.isEmpty(itServerDevice.getCcTimeStr())) {
            Instant instant = NGSMDateTimeFormatter.sdf.parse(itServerDevice.getCcTimeStr()).toInstant();
            ZoneId zoneId = ZoneId.systemDefault();
            LocalDateTime localDateTime = instant.atZone(zoneId).toLocalDateTime();
            itServerDevice.setCcTime(localDateTime);
        }
        if (!StringUtils.isEmpty(itServerDevice.getSjTimeStr())) {
            Instant instant = NGSMDateTimeFormatter.sdf.parse(itServerDevice.getSjTimeStr()).toInstant();
            ZoneId zoneId = ZoneId.systemDefault();
            LocalDateTime localDateTime = instant.atZone(zoneId).toLocalDateTime();
            itServerDevice.setSjTime(localDateTime);
        }
        if (!StringUtils.isEmpty(itServerDevice.getWbTimeStr())) {
            Instant instant = NGSMDateTimeFormatter.sdf.parse(itServerDevice.getWbTimeStr()).toInstant();
            ZoneId zoneId = ZoneId.systemDefault();
            LocalDateTime localDateTime = instant.atZone(zoneId).toLocalDateTime();
            itServerDevice.setWbTime(localDateTime);
        }
        if (!StringUtils.isEmpty(itServerDevice.getFixTimeStr())) {
            Instant instant = NGSMDateTimeFormatter.sdf.parse(itServerDevice.getFixTimeStr()).toInstant();
            ZoneId zoneId = ZoneId.systemDefault();
            LocalDateTime localDateTime = instant.atZone(zoneId).toLocalDateTime();
            itServerDevice.setFixTime(localDateTime);
        }
        PlatformUserDto user = userCache.get(request);
        Set<String> roleNames = new HashSet<>(user.getRoles());
        if (itServerDevice.getDevId() == null ){
            //新增情况
            if (!"itadmin".equals(user.getUsername()) && !roleNames.contains("itadmin") && !roleNames.contains(SERVER_ADMIN)) {
                return PlatformResponse.failedMsg("addOrUpdateServer接口，没有该功能权限。");
            }
        } else {
            //修改情况
            if (!"itadmin".equals(user.getUsername()) && !roleNames.contains("itadmin") && !roleNames.contains(SERVER_ADMIN)){
                //查找记录
                ItServerDevice dev = serverService.findByDevId(itServerDevice.getDevId().toString());
                if (!dev.getUserId().equals(itServerDevice.getUserId())){
                    return PlatformResponse.failedMsg("addOrUpdateServer接口，没有该功能权限。");
                }
            }
        }


        serverService.addOrUpdateServer(itServerDevice);
        return PlatformResponse.successMsg("创建或修改成功");
    }

    @RequestMapping(method = RequestMethod.POST, value = "delete")
    @ApiOperation(value = "删除", notes = "删除")
    public PlatformResponse<Void> deleteServerDevice(@RequestBody String devId) {
        if (devId == null) {
            return PlatformResponse.failedMsg("deleteServerDevice接口，id为空。");
        }
        PlatformUserDto user = userCache.get(request);
        Set<String> roleNames = new HashSet<>(user.getRoles());
        if (!"itadmin".equals(user.getUsername()) && !roleNames.contains("itadmin") && !roleNames.contains(SERVER_ADMIN)) {
            return PlatformResponse.failedMsg("deleteServerDevice接口，没有该功能权限。");
        }
        JSONObject jsonObject = (JSONObject) JSON.parse(devId);
        String id = jsonObject.getString("devId");
        if (StringUtils.isNotEmpty(id)) {
            serverService.deleteServer(id);
        }
        return PlatformResponse.successMsg("删除服务器成功");
    }

    //搜索服务器
    @RequestMapping(value = "/searchDevice", method = { RequestMethod.GET, RequestMethod.POST })
    public List<ItServerDevice> searchDevice(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String ssd = (String) request.getParameter("ssd");
        String isLikeString = request.getParameter("isLike");
        List<ItServerDevice> result = new ArrayList<>();
        if (StringUtils.isNotEmpty(isLikeString) && isLikeString.equals("true")){
            result = serverService.searchDevice(ssd,true);
        } else {
            result = serverService.searchDevice(ssd,false);
        }

        return result;
    }
    //查询全部服务器，不分页
    @RequestMapping(method = RequestMethod.GET, value = "listAll")
    @ApiOperation(value = "查询全部服务器", notes = "查询全部服务器")
    public PlatformResponse<List<ItServerDevice>> queryAllServer() {
        List<ItServerDevice> result = serverService.queryAllServer();
        return PlatformResponse.successData(result);
    }
//
//	//搜索服务器名称
//	@RequestMapping(value = "/multiSearch", method = { RequestMethod.GET, RequestMethod.POST })
//	public Object multiSearchDevice( com.jlwang.rest.serverdevice.boundary.ServerDeviceAddAndUpdateInput input,
//			HttpServletRequest request, HttpServletResponse response) throws Exception {
//		/*验证新增权限begin*/
//		String userId = CookieUtil.getParaFromCookie(request,"userId");
//		List<String> userRoles = userService.getUserAllRolesById(userId);
//		boolean isAuth = false; //是否有权限新增
//		for(String role:userRoles){
//			if("admin".equals(role)){
//				isAuth = true;
//				break;
//			}
//		}
//		if(!isAuth)
//			return new JsonResult(ErrorCode.E9999.getCode(), "抱歉，您未获得该权限，请联系管理员");
//		/*验证新增权限end*/
// 	Map<String, Object> serverDeviceList = BeanUtil.bean2Map(input);
//
//	List<Map<String, Object>> result =	serverDeviceService.multiSearchDevice(serverDeviceList);
//
//		JsonResult jsonResult = new JsonResult();
//		jsonResult.saveResultSet(result);        //保存搜索数据
//		return jsonResult;
//	}


    //搜索服务器
    @RequestMapping(method = RequestMethod.POST, value = "search")
    @ApiOperation(value = "搜索服务器", notes = "搜索服务器")
    public PlatformResponse<Page<ItServerDevice>> searchServer(@RequestBody ParamSearchServerDto params) {
        if (params.getPageNo() == null) {
            params.setPageNo(PageConstant.PageNo);
        }
        if (params.getPageSize() == null) {
            params.setPageSize(PageConstant.PageSize);
        }
        PlatformUserDto user = userCache.get(request);
        String userId = user.getUserid();
        Set<String> roleNames = new HashSet<>(user.getRoles());
        if ("itadmin".equals(user.getUsername()) || roleNames.contains("itadmin") || roleNames.contains(SERVER_ADMIN)) {
            userId = null;
        }
        String userAccount = params.getUserAccount();
        if (StringUtils.isNotEmpty(userAccount)) {
            PlatformUserDto u = userService.findByUsername(userAccount);
            if (u != null) {
                userId = u.getUserid();
            }
        }
        String businessName = params.getBusinessName();
        String applicationDetail = params.getApplicationDetail();
        String capitalStyle = params.getCapitalStyle();
        String capitalType = params.getCapitalType();
        String capitalTyped = params.getCapitalTyped();
        String ip1 = params.getIp1();
        String ip2 = params.getIp2();
        String machineCab = params.getMachineCab();
        String machineRoom = params.getMachineRoom();
        String machineStatus = params.getMachineStatus();
        String opStyle = params.getOpStyle();
        String sn = params.getSn();
        String operationSys = params.getOperationSys();

        if (StringUtils.isEmpty(params.getBusinessName())) {
            businessName = null;
        }
        if (StringUtils.isEmpty(params.getApplicationDetail())) {
            applicationDetail = null;
        }
        if (StringUtils.isEmpty(params.getCapitalType())) {
            capitalTyped = null;
        }
        if (StringUtils.isEmpty(params.getIp1())) {
            ip1 = null;
        }
        if (StringUtils.isEmpty(params.getIp2())) {
            ip2 = null;
        }
        if (StringUtils.isEmpty(params.getMachineCab())) {
            machineCab = null;
        }
        if (StringUtils.isEmpty(params.getSn())) {
            sn = null;
        }
//        if (params.getCapitalStyle() == null || params.getCapitalStyle() == 0) {
//            capitalStyle = null;
//        }
//        if (params.getMachineRoom() == null || params.getMachineRoom() == 0) {
//            machineRoom = null;
//        }
//        if (params.getMachineStatus() == null || params.getMachineStatus() == 0) {
//            machineStatus = null;
//        }
//        if (params.getOpStyle() == null || params.getOpStyle() == 0) {
//            opStyle = null;
//        }
//        if (params.getOperationSys() == null || params.getOperationSys() == 0) {
//            operationSys = null;
//        }

        Page<ItServerDevice> result = serverService.searchServer(params.getPageNo(), params.getPageSize(), businessName, applicationDetail, opStyle, machineRoom,
                machineCab, capitalTyped, capitalType, capitalStyle, ip1, ip2, sn, operationSys, userId, machineStatus,params);
        return PlatformResponse.successData(result);
    }


    //导出excel
    @RequestMapping(method = RequestMethod.POST, value = "exportServerOutPut")
    @ApiOperation(value = "导出excel", notes = "导出excel")
    public ResponseEntity<byte[]> exportServerOutPut() throws Exception {
//        /*验证新增权限begin*/
//        String userId = CookieUtil.getParaFromCookie(request, "userId");
//        List<String> userRoles = userService.getUserAllRolesById(userId);
//        boolean isAuth = false; //是否有权限新增
//        for (String role : userRoles) {
//            if ("admin".equals(role)) {
//                isAuth = true;
//                break;
//            }
//        }
//        if (!isAuth)
//            return new JsonResult(ErrorCode.E9999.getCode(), "抱歉，您未获得导出权限，请联系管理员");
        /*验证新增权限end*/
        List<ServerDeviceExport> result = serverService.queryServerOutPut();
        List<ExcelUtil.MultipleSheelPropety> list = new ArrayList<>();

        WriteSheet sheet = EasyExcel.writerSheet(0, "服务器").build();
        ExcelUtil.MultipleSheelPropety multipleSheelPropety = new ExcelUtil.MultipleSheelPropety();
        multipleSheelPropety.setData(result);
        multipleSheelPropety.setSheet(sheet);

        list.add(multipleSheelPropety);

        String fileName = itpath + "fwq.xlsx";
        ExcelUtil.writeWithMultipleSheel(fileName, list);

        String targetName = fileName;
        HttpHeaders headers = new HttpHeaders();
        ResponseEntity<byte[]> entity = null;
        InputStream in = null;
        in = new FileInputStream(new File(targetName));
        byte[] bytes = new byte[in.available()];
        String imageName = targetName;
        //处理IE下载文件的中文名称乱码的问题
        String header = request.getHeader("User-Agent").toUpperCase();
        if (header.contains("MSIE") || header.contains("TRIDENT") || header.contains("EDGE")) {
            imageName = URLEncoder.encode(imageName, "utf-8");
            imageName = imageName.replace("+", "%20"); //IE下载文件名空格变+号问题
        } else {
            imageName = new String(imageName.getBytes(), "iso-8859-1");
        }
        in.read(bytes);
        headers.add("Content-Disposition", "attachment;filename=" + imageName);
        entity = new ResponseEntity<byte[]>(bytes, headers, HttpStatus.OK);
        return entity;
    }

    //全部内容导出excel
    @RequestMapping(method = RequestMethod.POST, value = "export")
    @ApiOperation(value = "全部内容导出excel", notes = "全部内容导出excel")
    public ResponseEntity<byte[]> exportServerFullOutPut() throws Exception {
        /*验证新增权限begin*/
//        String userId = CookieUtil.getParaFromCookie(request, "userId");
//        List<String> userRoles = userService.getUserAllRolesById(userId);
//        boolean isAuth = false; //是否有权限新增
//        for (String role : userRoles) {
//            if ("admin".equals(role)) {
//                isAuth = true;
//                break;
//            }
//        }
//        if (!isAuth)
//            return new JsonResult(ErrorCode.E9999.getCode(), "抱歉，您未获得导出权限，请联系管理员");
        /*验证新增权限end*/
        List<ServerDeviceExportFull> result = serverService.queryServerFullOutPut();
        List<ExcelUtil.MultipleSheelPropety> list = new ArrayList<>();

        WriteSheet sheet = EasyExcel.writerSheet(0, "服务器全导出").build();
        ExcelUtil.MultipleSheelPropety multipleSheelPropety = new ExcelUtil.MultipleSheelPropety();
        multipleSheelPropety.setData(result);
        multipleSheelPropety.setSheet(sheet);

        list.add(multipleSheelPropety);

        String fileName = itpath + "fwq_all.xlsx";
        ExcelUtil.writeWithMultipleSheel(fileName, list);

        String targetName = fileName;
        HttpHeaders headers = new HttpHeaders();
        ResponseEntity<byte[]> entity = null;
        InputStream in = null;
        in = new FileInputStream(new File(targetName));
        byte[] bytes = new byte[in.available()];
        String imageName = targetName;
        //处理IE下载文件的中文名称乱码的问题
        String header = request.getHeader("User-Agent").toUpperCase();
        if (header.contains("MSIE") || header.contains("TRIDENT") || header.contains("EDGE")) {
            imageName = URLEncoder.encode(imageName, "utf-8");
            imageName = imageName.replace("+", "%20"); //IE下载文件名空格变+号问题
        } else {
            imageName = new String(imageName.getBytes(), "iso-8859-1");
        }
        in.read(bytes);
        headers.add("Content-Disposition", "attachment;filename=" + imageName);
        entity = new ResponseEntity<byte[]>(bytes, headers, HttpStatus.OK);
        return entity;
    }
//
//    private Map<String, Object> getFieldMap(ServerDeviceAddAndUpdateInput input) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
//        Map<String, Object> fieldMap = Maps.newHashMap();
//        Field[] fields = input.getClass().getDeclaredFields();
//        for (Field field : fields) {
//            Method m = input.getClass().getMethod("get" + field.getName().substring(0, 1).toUpperCase() + field.getName().substring(1));
//            Object type = m.invoke(input);
//
//            fieldMap.put(String.valueOf(field.getName()), type);
//        }
//        return fieldMap;
//    }
//


}
